import { Router, Request, Response } from 'express';
import { asyncHandler } from '../utils/asyncHandler';
import { createError } from '../middleware/errorHandler';

const router: Router = Router();

// Mock user data (replace with database operations)
interface User {
  id: number;
  name: string;
  email: string;
  createdAt: Date;
}

const mockUsers: User[] = [
  {
    id: 1,
    name: 'John Doe',
    email: 'john@example.com',
    createdAt: new Date()
  },
  {
    id: 2,
    name: 'Jane Smith',
    email: 'jane@example.com',
    createdAt: new Date()
  }
];

// GET /api/v1/users - Get all users
router.get('/', asyncHandler(async (req: Request, res: Response) => {
  const { page = 1, limit = 10 } = req.query;
  
  const startIndex = (Number(page) - 1) * Number(limit);
  const endIndex = startIndex + Number(limit);
  
  const paginatedUsers = mockUsers.slice(startIndex, endIndex);
  
  res.json({
    success: true,
    data: paginatedUsers,
    pagination: {
      page: Number(page),
      limit: Number(limit),
      total: mockUsers.length,
      pages: Math.ceil(mockUsers.length / Number(limit))
    }
  });
}));

// GET /api/v1/users/:id - Get user by ID
router.get('/:id', asyncHandler(async (req: Request, res: Response) => {
  const { id } = req.params;
  const user = mockUsers.find(u => u.id === Number(id));
  
  if (!user) {
    throw createError('User not found', 404);
  }
  
  res.json({
    success: true,
    data: user
  });
}));

// POST /api/v1/users - Create new user
router.post('/', asyncHandler(async (req: Request, res: Response) => {
  const { name, email } = req.body;
  
  if (!name || !email) {
    throw createError('Name and email are required', 400);
  }
  
  // Check if email already exists
  const existingUser = mockUsers.find(u => u.email === email);
  if (existingUser) {
    throw createError('Email already exists', 400);
  }
  
  const newUser: User = {
    id: mockUsers.length + 1,
    name,
    email,
    createdAt: new Date()
  };
  
  mockUsers.push(newUser);
  
  res.status(201).json({
    success: true,
    data: newUser,
    message: 'User created successfully'
  });
}));

// PUT /api/v1/users/:id - Update user
router.put('/:id', asyncHandler(async (req: Request, res: Response) => {
  const { id } = req.params;
  const { name, email } = req.body;
  
  const userIndex = mockUsers.findIndex(u => u.id === Number(id));
  
  if (userIndex === -1) {
    throw createError('User not found', 404);
  }
  
  if (name) mockUsers[userIndex].name = name;
  if (email) {
    // Check if email already exists (excluding current user)
    const existingUser = mockUsers.find(u => u.email === email && u.id !== Number(id));
    if (existingUser) {
      throw createError('Email already exists', 400);
    }
    mockUsers[userIndex].email = email;
  }
  
  res.json({
    success: true,
    data: mockUsers[userIndex],
    message: 'User updated successfully'
  });
}));

// DELETE /api/v1/users/:id - Delete user
router.delete('/:id', asyncHandler(async (req: Request, res: Response) => {
  const { id } = req.params;
  const userIndex = mockUsers.findIndex(u => u.id === Number(id));
  
  if (userIndex === -1) {
    throw createError('User not found', 404);
  }
  
  mockUsers.splice(userIndex, 1);
  
  res.json({
    success: true,
    message: 'User deleted successfully'
  });
}));

export default router;